import { View } from "@tarojs/components";
import style from "./index.module.scss";
import { RowCenter } from "../Flex";
import clsx from "clsx";
import { useEffect, useState } from "react";

/**
 * 通用弹框类组件
 * 弹框类型type
 *   center: 居中
 *   pullUp: 底部拉起
 *   pullDown: 顶部掉下
 *   pullLeft: 左侧弹出
 *   pullRight: 右侧弹出
 * @param {*} props
 * @returns
 */
export function Dialog(props) {
  let {
    show = false,
    children,
    type = "center",
    onBlankClick,
    showMask = true,
  } = props;

  const [_show, setShow] = useState(show);
  const [bgClass, setBgClass] = useState(undefined);
  const [boxClass, setBoxClass] = useState(undefined);

  // 确保弹框类型合法
  if (
    !["center", "pullUp", "pullDown", "pullLeft", "pullRight"].includes(type)
  ) {
    type = "center";
  }
  const Container = type === "center" ? RowCenter : View;

  useEffect(() => {
    if (show) {
      setShow(true);
      setBgClass(clsx(style.bg, style.bgShow));
      setBoxClass(clsx(style.box, style[type], style[`${type}Show`]));
    } else {
      setBgClass(clsx(style.bg, style.bgHide));
      setBoxClass(clsx(style.box, style[type], style[`${type}Hide`]));
    }
  }, [show]);

  // 内部状态_show为不显示的时候，渲染空组件
  if (!_show) return null;

  // 内部组件_show为显示的时候，渲染组件
  return (
    <Container className={style.container}>
      <View
        className={showMask ? bgClass : clsx(style.bg, style.bgTransparent)}
        onClick={(event) => {
          // 空白处点击触发回调
          if (event.target.id === event.currentTarget.id) {
            onBlankClick?.(event);
          }
        }}
      />
      <View
        className={boxClass}
        onAnimationEnd={(event) => {
          const ucType = type[0].toUpperCase() + type.substring(1);
          if (event.detail.animationName === style[`${ucType}Hide`]) {
            setShow(false);
          }
        }}
      >
        {children}
      </View>
    </Container>
  );
}
